package br.inf.solutions.apresentacoes.ssp.view.composer.basicforms;

import org.zkoss.zk.ui.Component;
import org.zkoss.zul.Row;
import org.zkoss.zul.Window;

import br.com.vexillum.model.CommonEntityActivated;
import br.com.vexillum.util.Return;
import br.inf.solutions.apresentacoes.ssp.control.basics.BasicFormsController;
import br.inf.solutions.apresentacoes.ssp.view.composer.BaseComposer;

@SuppressWarnings("serial")
public abstract class BasicFormsComposer<E extends CommonEntityActivated, G extends BasicFormsController<E>> extends BaseComposer<E, G> {

	private Boolean listInactives = false;
	
	public Row rowAtivo;
	
	public Boolean getListInactives() {
		return listInactives;
	}

	public void setListInactives(Boolean listInactives) {
		this.listInactives = listInactives;
	}

	public void setParentComposer(BasicFormsComposer<E, G> parentComposer) {
		this.parentComposer = parentComposer;
	}
	
	@SuppressWarnings("unchecked")
	public void doAfterCompose(Component comp) throws Exception {
		super.doAfterCompose(comp);	
		if(arg.get("selectedEntity") != null){
			entity = (E) arg.get("selectedEntity");
			update = true;			
		}
		disableRowAtivo();
		loadBinder();
		if(!update){
			doAction("listAll");
		}
		chechReportButton();
	}
	
	public void disableRowAtivo() {
		Row linha = (Row) getComponentById(component, "rowAtivo");
		
		if(linha != null && !update){
			linha.setVisible(false);
		}
	}
	
	public void callUpdateModal(){
		Return ret = validateSelectedEntity();
		if(ret.isValid()){
			super.callModalWindow(getUpdatePage());
		}
	}
	
	public void callDeactivationConfirmation(){
		super.showDeactivateConfirmation(getDeactivationMessage());
	}
	
	protected abstract String getUpdatePage();
	
	protected String getDeactivationMessage() {
		return "Tem certeza que deseja desativar?";
	}
	
	protected String getActivationMessage() {
		return "Tem certeza que deseja ativar?";
	}
	
	public void callActivationConfirmation(){
		super.showActivateConfirmation(getActivationMessage());
	}
	
	@Override
	public Return saveEntity() {
		Return ret = super.saveEntity();
		if(ret.isValid() && getUpdate()){
			getParentComposer().loadBinder();
			((Window) getComponentById(component, "modalWindow")).detach();
		} else if (ret.isValid()) {
			clearForm();
		}
		loadBinder();
		ret.concat(listAll());
		return ret;
	}
	
	@Override
	public Return listAll() {
		getEntity().setActive(!getListInactives());
		return super.listAll();
	}

}
